package io.netty.example.a;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author: pch
 * @description:
 * @date: 2021/5/28
 **/
public class EchoClient {
	private final String host;//远程IP
	private final int port;//远程端口

	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public static void main(String[] args) {
		new EchoClient("127.0.0.1", 9999).start();
	}

	public void start() {
		// 客户端只需要一个WorkerGroup
		NioEventLoopGroup worker = new NioEventLoopGroup();

		new Bootstrap()
				.group(worker)
				.channel(NioSocketChannel.class)
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel sc) throws Exception {
						sc.pipeline().addLast(new ChannelInboundHandlerAdapter() {
							@Override
							public void channelActive(ChannelHandlerContext ctx) throws Exception {
								super.channelActive(ctx);
								System.out.println("连接建立,开始发送【hello】...");
								ctx.writeAndFlush(Unpooled.wrappedBuffer("hello".getBytes()));
							}

							@Override
							public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
								String data = ((ByteBuf) msg).toString(Charset.defaultCharset());
								System.out.println("收到服务端数据:" + data);
							}
						});
					}
				}).connect(host, port);//连接服务端
	}
}